package com.star.spring.deferred.service.completable;


import com.star.spring.deferred.utils.CommonUtils;

import java.util.concurrent.CompletableFuture;

/**
 * @description: compile
 * @author: star
 * @create: 2024-12-24 23:24
 **/

public class ThenCombine {

    // 获取iphone在京东的价格
    // 获取iphone在京东的优惠
    // 获取之后计算优惠后的价格

    public static void main(String[] args) {

        long start = CommonUtils.getTimestamp();

//        Integer finalPrice = function1();   5s
        Integer finalPrice = function2();

        long end = CommonUtils.getTimestamp();

        // 计算耗时（s）
        System.out.println("耗时：" + (end - start) / 1000 + "s");

    }

    private static Integer function1() {
        Integer price = getPrice();
        Integer discount = getDiscount();
        return getFinalPrice(price, discount);
    }


    private static Integer function2() {
        CompletableFuture<Integer> integerCompletableFuture = CompletableFuture.supplyAsync(() -> {

                    CommonUtils.sleep(1);
                    CommonUtils.log("获取价格");
                    return getPrice();
                })
                .thenCombine(CompletableFuture.supplyAsync(() -> {
                    CommonUtils.log("获取优惠");
                    return getDiscount();
                }), (price, discount) -> {
                    CommonUtils.log("计算最终价格");
                    return getFinalPrice(price, discount);
                });
        try {
            return integerCompletableFuture.get();
        } catch (Exception e) {
            e.printStackTrace();
            return 0;
        }
    }


    public static Integer getPrice() {
        CommonUtils.sleep(3);
        return 6000;
    }

    public static Integer getDiscount() {
        CommonUtils.sleep(2);
        return 500;
    }

    public static Integer getFinalPrice(Integer price, Integer discount) {
        return price - discount;
    }
}
